<?php
namespace App\Models\User;

use App\Libs\Base\Constant;
use App\Libs\Helper\CommonHelper;
use App\Models\Member\MemberLevel;
class User extends \App\Libs\Base\BaseModel
{ 
    protected $__TABLE__ = 't_jia_user_info';
	protected static $salt = 'Just-4#Holp';
    private function generate($identify) {
        return  md5(md5($identify . ':' . mt_rand(1, 1000)) . microtime(true));
    }
	
	/**
	*	跳过检测了
	*/
	public function beforeValidation()
	{
	  self::skipValidation(['utime','total_time','balance','username','avatar','credential_type','credential_no','email','unionid','openid','baby_name','baby_sex','baby_birthday','baby_parents','address','total_credit','area','week_time','week_credit'] , $this );
	}
	
	/**
	*	注册
	*/
    public function regist($infos) {
		// phone is not regist
		
		/*$params = array(
			'phone = ?0',
			'bind' => array($infos['phone']),
		);
		if (self::find($params)) {
			return -1;
		}
		// username is unique
		$params = array(
			'username = ?0',
			'bind' => array($infos['username']),
		);
		if (self::find($params)) {
			return -2;
		}*/

        $token = $this->getUniqueToken($infos);
        $infos['token'] = $token;
        $infos['ctime'] = date('Y-m-d H:i:s');
		$infos['username'] = \App\Libs\Helper\CommonHelper::randomChat();
		$infos['avatar'] = \App\Libs\Base\Config::instance()->common['commonAvatar'];
		$infos['baby_name'] = '';
		$infos['baby_sex'] = '0';
		$infos['baby_birthday'] = '';
		$infos['home_price'] = 0;
		$infos['expand'] = 0;
		$infos['vip'] = 0;
        //$infos['password'] = md5($infos['password'] . ':' . self::$salt);

		unset($infos['id']);
		foreach ($infos as $field => $value) {
			$this->{$field} = $value;
		}
		$this->save();
		\App\Libs\Session\Session::regist($this);
		return $this->id;
    }
	
	/**
	*	登录密码
	*/
	public function login($password) {
		$isfit = md5($password . ':' . self::$salt) === $this->password;
		if ($isfit) {
			// set session
			\App\Libs\Session\Session::regist($this);
		}

		return $isfit;
	}	

	/**
	*	检查验证码
	*/
	public function loginCaptcha($captcha) {
		$key = 'captcha:' . $this->phone;
		//$store = \App\Libs\Cache\Redis::get($key);
		$store = '1234';
		if ($store === strtolower($captcha)) {
			if (isset($this->id)) {
				\App\Libs\Session\Session::regist($this);
			}
			return TRUE;
		}

		return FALSE;
	}

    public function getUniqueToken($info) {
        // generate token
        $identify = '';
        if (!empty($info['phone'])) {
            $identify = $info['phone'];
        } else if (!empty($info['wx_unionid'])) {
            $identify = $info['wx_unionid'];
        } else {
            $identify = $info['username'];
        }
		$retry = 5;
        do {
            $token = $this->generate($identify);

            $isExist = self::getUserByToken($token);

			if ($retry <= 0) {
				throw \App\Libs\Exception\RuntimeException::instance(Constant::RESOURCE_MISSING);
			}
			$retry --;
        } while($isExist);

        return $token;
    }

    public static function getUserByToken($token) {
		return self::findOne(array(
			'token = ?0',
			'bind' => array($token),
		));
    }


    public function getUserInfo($userIdAray)
    {
        $userInfo = self::findAll([
            'conditions' => 'id IN ({userIdAray:array})',
            'columns' => 'id as uid,username,avatar',
            'bind' => ['userIdAray' => $userIdAray]
        ])->toArray();
        return $userInfo;
    }

    /**
     *      合并用户的信息和他们的评论
     * @param $user  用户id数组
     * @param $userCmt   用户评论数组
     * @return array  合并后的数据
     */
    public function mergeUfoAndCmt($user, $userCmt)
    {
        $userInfo = $this->getUserInfo($user);
        $topUserInfo = CommonHelper::setColToKey($userInfo, 'uid');
        foreach ($userCmt as $key => $val) {
	
            $cmtAndUserInfo[] = array_merge($userCmt[$key], $topUserInfo[$userCmt[$key]['uid']]);
        }
        return $cmtAndUserInfo;
    }

/*    public function afterFetch()
    {
        $this->balance = Goods::formatPrice($this->balance);
    }
*/


    public static function secToTime($time){
        if(is_numeric($time)){
            $value = array(
                "years" => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            if($time >= 31556926){
                $value["years"] = floor($time/31556926);
                $time = ($time%31556926);
            }
            if($time >= 86400){
                $value["days"] = floor($time/86400);
                $time = ($time%86400);
            }
            if($time >= 3600){
                $value["hours"] = floor($time/3600);
                $time = ($time%3600);
            }
            if($time >= 60){
                $value["minutes"] = floor($time/60);
                $time = ($time%60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;

            if(!empty($value['years'])) {
                return $value["years"] . "年" . $value["days"] . "天";
            }elseif (!empty($value['days'])){
                return $value["days"] ."天"." ". $value["hours"] ."小时";
            }elseif (!empty($value['hours'])){
                return $value["hours"] ."小时". $value["minutes"] ."分";
            }elseif(!empty($value['minutes'])){
                return $value["minutes"] ."分";
            }else{
                return '不足一分钟';
            }
        }else{
            return (bool) FALSE;
        }
    }

    public static function secToIntTime($time){
        if(is_numeric($time)){
            if($time >= 3600){
                $hours = floor($time/3600);
            }else{
                $hours = 0;
            }
            $leftSec = $time-($hours*60*60);
            if(!empty($leftSec)){
                $min = floor($leftSec/60);
                $percentMin = $min/60;
            }else{
                $percentMin = 0;
            }
            if(empty($hours) && empty($percentMin)){
                return 0;
            }else{
                return round($hours+$percentMin,2);
            }
        }else{
            return (bool) FALSE;
        }
    }


    public static function  getMedalLevel($sec){
        $data= [];
        $level = MemberLevel::findAll();
        $level->rewind();
        while($level->valid()){
            $curr = $level->current();
            $data[$curr->level]['levelMember'][] = $curr->toArray(['level','hour','credits']);
            $level->next();
        }
        foreach($data as $key =>  $val){
            $data[$key]['level'] = $key;
        }
        foreach ($data as $level => $levelData){
            $sortArray = self::sortKey($data[$level]['levelMember'],'hour');
            $data[$level]['maxTime'] = $sortArray[count($sortArray)-1]['hour'];
        }
        $transData = CommonHelper::setColToKey($data,'level');
        foreach ($transData as $key => $val){
            if($key<=1){
                $transData[$key]['min'] = 0;
                $transData[$key]['max'] = $transData[$key]['maxTime']*60*60;
            }else{
                $transData[$key]['min'] = $transData[$key-1]['maxTime']*60*60+1;
                $transData[$key]['max'] = $transData[$key]['maxTime']*60*60;
            }
        }
        foreach($transData as $key => $val){
            if($sec>=$val['min'] && $sec<$val['max']){
                return $key;
            }else{
                return 5;
            }
        }

    }


    public static function sortKey($array,$key){
        $transArray = CommonHelper::setColToKey($array,$key);
        ksort($transArray,SORT_NUMERIC );
        return array_values($transArray);
    }

    public function getMyMedalNum(){
        $level = MemberLevel::findAll();
        $level->rewind();
        while($level->valid()){
            $cur = $level->current();
            $curArray = $cur->toArray(['id','hour','level','credits','icon']);
            $curArray['max_time'] = $cur->hour*60*60;
            $newData[] =$curArray;
            $level->next();
        }
        foreach($newData as $key => $val){
            if(((int)$key-1) == -1){
                $newData[$key]['min_time'] = 0;
            }else{
                $newData[$key]['min_time'] = $newData[$key-1]['max_time']+1;
            }
        }
        $sec = $this->total_time;
        $medalId = [];
        foreach($newData as $key => $val){
            if($sec>=$newData[$key]['max_time']){
                $medalId[] = $newData[$key]['id'];
            }
        }
        return count($medalId);
    }



}
